package com.hello.gateway.filter;

import com.hello.gateway.utils.GatewayLogUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Optional;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;

/**
 * 网关全局日志过滤器
 * 
 * @author hello
 */
@Component
public class GatewayLogFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求路径
        String requestPath = request.getURI().getPath();
        // 获取路由ID
        Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
        String routeId = Optional.ofNullable(route).map(Route::getId).orElse("未知路由");
        
        // 记录请求开始日志
        GatewayLogUtils.logRouteStart(exchange, routeId);
        
        // 记录请求处理时间
        long startTime = System.currentTimeMillis();
        
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // 计算处理时间
            long executionTime = System.currentTimeMillis() - startTime;
            
            // 记录请求完成日志
            GatewayLogUtils.logRouteComplete(exchange, routeId, executionTime);
        }));
    }

    @Override
    public int getOrder() {
        // 确保此过滤器在最外层执行，可以记录完整的处理过程
        return Ordered.HIGHEST_PRECEDENCE;
    }
} 